#include "LogFile.h"
#include "TimeUtility.h"


LogFile::LogFile()
{
	logBuffer="";

	string logFileName="log.txt";
	
	char buffer[MAX_PATH];
	GetModuleFileName(NULL,buffer,MAX_PATH);
	string filePath=buffer;
	filePath=filePath.erase(filePath.rfind('\\')+1);
		
	//if log file is greater than a certain limit, rename the old file
	if(GetFileSize(filePath+logFileName)>1048576)
	{
		string newFilename=filePath+TimeUtility::Now(true)+" "+logFileName;
		rename((filePath+logFileName).c_str(),newFilename.c_str());
	}

	logFilePath=filePath+logFileName;
}
LogFile::~LogFile()
{
	Flush();
}
void LogFile::Log(const string& line)
{
	logBuffer+=TimeUtility::Now()+": "+line+"\n";
}
void LogFile::Flush()
{
	try
	{
		ofstream fileStream(logFilePath,ios::out|ios::app);
		if (fileStream.is_open())
		{
			fileStream<<logBuffer;
			fileStream.close();
			logBuffer="";
		}
		fileStream.close();
	}
	catch(...)
	{
	}
}
int LogFile::GetFileSize(const string& filename)
{
	fstream fileStream(filename.c_str());
	if(fileStream.is_open())
	{
		fileStream.seekg(0,ios::end);
		int length=(int)fileStream.tellg();
		fileStream.close();
		return length;
	}
	fileStream.close();
	return 0;
}